package actions;

import objects.MessageCodes;
import objects.cluster.ClusterInfo;
import objects.cluster.ClusterLoginData;
import objects.shared.Message;
import objects.user.UserInfo;
import utils.MessageStrings;
import database.Database;

public class ClusterFunctions implements MessageCodes {
	
	public static Object[] clusterLogin(ClusterLoginData cli, String hostname) throws Exception
	{
		if(hostname == null) 
			return new Object[]{new Message(ERR),null,null};
		
		String uname = cli.user;
		String passwd = cli.pass;
		UserInfo ui;
		ClusterInfo ci;
		if((ui = Database.users.get(uname)) == null || !ui.getPasswd().equals(passwd))
		{
			return new Object[]{new Message(USR_ERR,MessageStrings.invalidCred),null,null};
		}
		
		//info was already in database
		if((ci=Database.getClusterInfo(hostname, cli.host)) == null)
		{
			//new cluster is registering
			ci = new ClusterInfo(hostname,cli.host);
			if(Database.registerCluster(ui, ci) == SQL_ERR) {
				return new Object[]{new Message(SQL_ERR,MessageStrings.sqlError),null,null};
			}
			
		}
		ui.clusterMap.put(ci.db_id,ci);
		//TODO uncomment
		/*else if(ci.isConnected)
		{
			return new Object[]{new Messag(ERR),null,null};
		}*/
		
		ci.local_hostname = cli.host;
		return new Object[]{new Message(OK),ui,ci};
	}
}
